package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: EmployeeController
 * @Description:
 * @Author: zhangcheng
 * @DateTime: 2022/6/6 9:30
 * @Version 1.0
 */

/**
 * 员工管理
 */
@Slf4j
@Transactional
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        List<Employee> employees = employeeService.list();
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("员工信息");
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("用户名");
        row.createCell(2).setCellValue("账号");
        row.createCell(3).setCellValue("密码");
        row.createCell(4).setCellValue("电话");
        row.createCell(5).setCellValue("性别");
        row.createCell(6).setCellValue("身份证号");
        row.createCell(7).setCellValue("状态");
        row.createCell(8).setCellValue("创建时间");
        row.createCell(9).setCellValue("更新时间");
        row.createCell(10).setCellValue("创建人");
        row.createCell(11).setCellValue("更新人");

        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            HSSFRow hr = sheet.createRow(i + 1);
            hr.createCell(0).setCellValue(Long.toString(employee.getId()));
            hr.createCell(1).setCellValue(employee.getName());
            hr.createCell(2).setCellValue(employee.getUsername());
            hr.createCell(3).setCellValue(employee.getPassword());
            hr.createCell(4).setCellValue(employee.getPhone());
            hr.createCell(5).setCellValue(employee.getSex().equals("1") ? "男" : "女");
            hr.createCell(6).setCellValue(employee.getIdNumber());
            hr.createCell(7).setCellValue(employee.getStatus() == 1 ? "启用" : "禁用");
            hr.createCell(8).setCellValue(employee.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            hr.createCell(9).setCellValue(employee.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            hr.createCell(10).setCellValue(employeeService.getById(employee.getCreateUser()).getName());
            hr.createCell(11).setCellValue(employeeService.getById(employee.getUpdateUser()).getName());

        }

        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=employee.xlsx");
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
/*        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=employee.xlsx");
            FileInputStream is = new FileInputStream(new File("G:\\img\\","aaa.xlsx"));
            ServletOutputStream os = response.getOutputStream();
            IOUtils.copy(is,os);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }*/


    /**
     * 用户登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //比对账号是否存在
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);

        if (emp == null) {
            return R.error("账号不存在");
        }

        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误,请重新输入");
        }

        if (emp.getStatus() == 0) {
            return R.error("该账号已被禁用,请联系管理员");
        }
        //将登陆成功的用户id 存储到session中
        request.getSession().setAttribute("employee", emp.getId());
        //将密码设为null,避免泄露
        emp.setPassword(null);
        return R.success(emp);

/*        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(lqw);

        if (emp == null){
            return R.error("该账号不存在");
        }

        if (!emp.getPassword().equals(password)){
            return R.error("密码错误");
        }

        if (emp.getStatus()==0){
            return R.error("账号已禁用");
        }

        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);*/
    }

    /**
     * 员工退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清除Session数据
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     *
     * @param
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        log.info("新增员工,员工信息为:{}", employee.toString());

        //如果不用全区异常处理,可以直接先判断 账号 是否存在
/*        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);
        if (emp != null) {
            return R.error("账号" + employee.getUsername() + "已存在");
        }*/

        //设置初始密码123456,并进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //获取当前登录用户的id
        //Long empId = (Long) request.getSession().getAttribute("employee");
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        IPage<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name), Employee::getName, name);

        employeeService.page(pageInfo, lqw);


        Map data = new HashMap();
        data.put("records", pageInfo.getRecords());
        data.put("total", pageInfo.getTotal());

        return R.success(data);



/*        //分页构造器
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name),Employee::getName,name);
        lqw.orderByDesc(Employee::getUpdateTime);
        //带条件的分页查询
        employeeService.page(pageInfo,lqw);
        return R.success(pageInfo);*/
    }

    /**
     * 修改员工信息(禁用启用状态)
     *
     * @param
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        //employee.setUpdateTime(LocalDateTime.now());
        //Long id = (Long) request.getSession().getAttribute("employee");
        //employee.setUpdateUser(id);

        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据id查询员工信息...");

        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }
}
